<template>
    <div>

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="价格" prop="price">
                <el-input v-model="ruleForm.price"></el-input>
            </el-form-item>

            <el-form-item label="标题" prop="title">
                <el-input type="textarea" v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="付款人数" prop="payment">
                <el-input type="textarea" v-model="ruleForm.payment"></el-input>
            </el-form-item>
            <el-form-item label="是否包邮">
                <el-switch v-model="ruleForm.free_shipping"></el-switch>
            </el-form-item>
            <el-form-item label="商店名字" prop="ShopName">
                <el-input type="textarea" v-model="ruleForm.ShopName"></el-input>
            </el-form-item>
            <el-upload
                    class="avatar-uploader"
                    action="#"
                    :http-request="httpRequest"
                    :auto-upload="true"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"

            >
                <el-image v-if="imageUrl" :src="imageUrl" class="avatar" fit="contain" ></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>


            </el-upload>
            <el-progress :percentage="uploadMessage"></el-progress>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')  ">提交</el-button>

                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>

        </el-form>

    </div>

</template>

<script>
    export default {
        name: "Upload",
        data() {
            return {
                ruleForm: {
                    price: '',
                    title:'',
                    payment:'',
                    free_shipping: false,
                    ShopName:"",
                },
                rules: {
                    price: [
                        {required: true, message: '请输入价格', trigger: 'blur'},

                    ],
                    title: [
                        {required: true, message: '请填写标题', trigger: 'blur'}
                    ],payment: [
                        {required: true, message: '付款人数', trigger: 'blur'}
                    ],
                    ShopName: [
                        {required: true, message: '请填写商店名字', trigger: 'blur'}
                    ]
                },
                iconformData:{
                    img:'',
                    name:'',

                },
                imageUrl: '',
                file:'',
                uploadMessage:0

            };
        },
        methods: {

            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var _free_shipping = 0
                        if(this.ruleForm.free_shipping){
                             _free_shipping = 1
                        }else{
                             _free_shipping = 0
                        }
                        axios.get("http://www.qjhyuki.top/vuehomeword/VueShop/api/upload_commodity.php", {
                            params: {
                                title: this.ruleForm.title,
                                price: this.ruleForm.price,
                                ShopName: this.ruleForm.ShopName,
                                free_shipping: _free_shipping,
                                payment: this.ruleForm.payment,
                                photo :this.iconformData.name

                            }
                        })
                        this.saveIco()
                    } else {
                        console.log('error submit!!');
                        return false;
                    }

                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }, handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            createCode(codeLength=6) {
                let code = '';
                //设置长度，这里看需求，我这里设置了4


                //设置随机字符
                const random = new Array("a","b","c","d","e", "f", "g", "h","i", "j","k", "l","m","n", "o","p","q", "r","s","t", "u","v","w","x","y","z");

                //循环codeLength 我设置的4就是循环4次
                for (let i = 0; i < codeLength; i++) {
                    //设置随机数范围,这设置为0 ~ 36
                    const index = Math.floor(Math.random() * 9);

                    //字符串拼接 将每次随机的字符 进行拼接
                    code += random[index];
                }

                //将拼接好的字符串赋值给展示的code
                return code
            },
            httpRequest(data) {

                let _this = this
                let rd = new FileReader() // 创建文件读取对象
                let file = data.file
                rd.readAsDataURL(file) // 文件读取装换为base64类型
                rd.onloadend = function (e) {
                    _this.imageUrl = this.result // this指向当前方法onloadend的作用域
                    _this.iconformData.img = this.result

                }
                _this.data = data

                const fileArr = data.file.name.split('.')
                const suffix = fileArr[fileArr.length -1]
                const name = new Date().getTime()+this.createCode(6) +"."+suffix
                this.iconformData.name =name;
                console .log(this.iconformData)



            },

            beforeAvatarUpload(file) {

                const isLt5M = file.size / 1024 / 1024 < 10;


                if (!isLt5M) {
                    this.$message.error('上传封面图片大小不能超过 10MB!');
                }


                return  isLt5M;
            },

            saveIco(){
                var _this = this
                const formData = new FormData()
                for (const key in this.iconformData) {
                    formData.append(key, this.iconformData[key]);//传参改为formData格式
                }


                axios
                    .post(
                        "http://www.qjhyuki.top/vuehomeword/VueShop/api/upload_photo.php",//请求后端的url
                        formData,
                        {

                            timeout: 1000000,
                            headers: {
                                "Content-Type": "multipart/form-data",//设置headers
                                // token: getToken()
                            },
                            onUploadProgress: progressEvent => {
                                let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                                _this.uploadMessage = complete

                            }}

                    )
                    .then(({data}) => {

                        if (data === 1) {
                            alert('提交成功!');
                            this.$router.push({path:'/admin_manage'})
                            window.location.reload();

                        } else {
                            alert('提交失败!');
                        }
                    })


        }
    }}
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>